/**
 * 模块在安装过程中的预准备工作
 * Copyright(C) 2018 liumurong
 * 
 * 1.拷贝相关动态库
 */

import * as fs from "fs";
import * as path from 'path';
import * as os from 'os';
import * as cp from 'child_process';

let dllDir = path.join(__dirname, "./third/lib/");
let srcDir = path.join(__dirname, "./build/Release/");

let platform = os.platform();

if (platform === "win32") {
    // windows平台，首先编译动态库，然后再将依赖库拷贝到生成目录
    let bat = cp.spawnSync("node-gyp rebuild", [], { cwd: __dirname, shell: true, windowsHide: true });
    let files = fs.readdirSync(dllDir);
    if (files && files.length > 0) {
        for (let i = 0; i < files.length; i++) {
            let ele = files[i];
            if (path.extname(ele) === ".dll") {
                let filePath = path.join(dllDir, ele);
                let desFilePath = path.join(srcDir, ele);
                fs.createReadStream(filePath).pipe(fs.createWriteStream(desFilePath));
            }
        }
    }
} else if (platform === "linux") {
    // 1. 拷贝.a和.so文件
    let libDesPath = "/usr/lib";
    let files = fs.readdirSync(dllDir);
    if (files && files.length > 0) {
        for (let i = 0; i < files.length; i++) {
            let ele = files[i];
            if (path.extname(ele) === ".a" || path.extname(ele) === ".so" || path.extname(ele) === ".2") {
                let filePath = path.join(dllDir, ele);
                let desFilePath = path.join(libDesPath, ele);
                let buf = fs.readFileSync(filePath);
                fs.writeFileSync(desFilePath, buf);
                //fs.createReadStream(filePath).pipe(fs.createWriteStream(desFilePath));
            }
        }
    }
    // 2. 注册库
    let sh1 = cp.spawnSync("ldconfig", [], { cwd: __dirname, shell: true });
    console.log(sh1.stdout && sh1.stdout.toString());
    console.log(sh1.stderr && sh1.stderr.toString());
    // 编译模块
    let sh2 = cp.spawnSync("node-gyp", ["rebuild"], { cwd: __dirname, shell: true });
    console.log(sh2.stdout && sh2.stdout.toString());
    console.log(sh2.stderr && sh2.stderr.toString());
}


